<?php
!function_exists('adminmsg') && exit('Forbidden');
$basename = "$admin_file?adminjob=creathtm&type=$type";

$sqladd = "WHERE type<>'category' AND allowvisit='' AND f_type!='hidden' AND cms='0'";

if (!$action) {

	@include_once(D_P.'data/bbscache/forumcache.php');
	$num = 0;
	$forumcheck = "<table cellspacing='0' cellpadding='0' border='0' width='100%' align='center'><tr>";

	$select = '';
	$query	= $db->query("SELECT fid,name,allowhtm FROM pw_forums $sqladd");
	while ($rt = $db->fetch_array($query)) {
		$num++;
		$htm_tr = $num % 5 == 0 ? '</tr><tr>' : '';
		$checked = $rt['allowhtm'] ? 'checked' : $checked='';
		$forumcheck .= "<td><input type='checkbox' name='selid[]' value='$rt[fid]' $checked>$rt[name]</td>$htm_tr";
		$rt['allowhtm'] && $select .= "<option value=\"$rt[fid]\">$rt[name]</option>";
	}
	$forumcheck.="</tr></table>";
	include PrintEot('creathtm');exit;

} elseif ($_POST['action'] == 'submit') {

	InitGP(array('selid'),'P');
	$selid = checkselid($selid);
	if ($selid === false) {
		$basename = "javascript:history.go(-1);";
		adminmsg('operate_error');
	} elseif ($selid == '') {
		$db->update("UPDATE pw_forums SET allowhtm='0' $sqladd");
	} elseif ($selid) {
		$db->update("UPDATE pw_forums SET allowhtm='1' $sqladd AND fid IN($selid)");
		$db->update("UPDATE pw_forums SET allowhtm='0' $sqladd AND fid NOT IN($selid)");
	}
	updatecache_f();
	adminmsg('operate_success');

} elseif ($action == 'creat') {

	@set_time_limit(0);
	$pwServer['REQUEST_METHOD']!='POST' && PostCheck($verify);
	InitGP(array('creatfid','percount','step','tfid','forumnum'));

	$fids = $tid = $fieldadd = $tableadd = $tids = '';
	!is_array($creatfid) && $creatfid = explode(',',$creatfid);
	if (in_array('all',$creatfid)) {
		$query = $db->query("SELECT fid FROM pw_forums $sqladd AND allowhtm='1'");
		while($rt = $db->fetch_array($query)){
			$fids.= ($fids ? ',' : '').$rt['fid'];
		}
		$creatfid = explode(',',$fids);
	} else {
		$fids = implode(',',$creatfid);
	}
	!$fids && adminmsg('template_noforum');

	!$tfid && $tfid = 0;
	$thisfid = (int)$creatfid[$tfid];

	$foruminfo = $db->get_one("SELECT * FROM pw_forums f LEFT JOIN pw_forumsextra fe USING(fid) WHERE f.type<>'category' AND f.allowvisit='' AND f.f_type!='hidden' AND f.cms='0' AND f.fid=".pwEscape($thisfid));
	if (!$foruminfo || !$foruminfo['allowhtm']) {
		adminmsg('template_error');
	}
	$forumname = strip_tags($foruminfo['name']);
	$forumset  = unserialize($foruminfo['forumset']);

	$output = 'readtpl';
	include_once Pcv(D_P."data/style/$db_defaultstyle.php");
	if (!file_exists(R_P."template/$tplpath/$output.htm")) {
		$tplpath='wind';
	}
	if (file_exists(D_P."data/style/{$tplpath}_css.htm")) {
		$css_path = D_P."data/style/{$tplpath}_css.htm";
	} else {
		$css_path = D_P.'data/style/wind_css.htm';
	}
	require_once(R_P.'require/forum.php');
	include_once(R_P.'require/template.php');
	include_once(D_P.'data/bbscache/forum_cache.php');
	include_once(D_P.'data/bbscache/customfield.php');
	include_once(D_P.'data/bbscache/md_config.php');
	if ($md_ifopen) {
		include_once(D_P.'data/bbscache/medaldb.php');
	}
	foreach ($customfield as $key => $val) {
		$val['id'] = (int)$val['id'];
		$fieldadd .= ",mb.field_$val[id]";
	}
	$fieldadd && $tableadd = "LEFT JOIN pw_memberinfo mb ON mb.uid=t.authorid";
	$creatadd	= "WHERE fid='$thisfid' AND ifcheck=1 AND t.special NOT IN(2,3)";

	$imgpath	= $db_http	!= 'N' ? $db_http : $db_picpath;
	$attachpath	= $db_attachurl	!= 'N' ? $db_attachurl : $db_attachname;
	$url		= "read.php";
	$ttable_a	= $ptable_a = array();

	$S_sql = ',m.uid,m.username,m.oicq,m.groupid,m.memberid,m.icon AS micon,m.hack,m.honor,m.signature,m.regdate, m.medals,m.userstatus,md.onlinetime,md.postnum,md.digests,md.rvrc,md.money,md.credit,md.currency,md.starttime,md.thisvisit,md.lastvisit,p.voteopts,p.modifiable,p.previewable,p.multiple,p.mostvotes,p.voters,p.timelimit';
	$J_sql = "LEFT JOIN pw_members m ON m.uid=t.authorid LEFT JOIN pw_memberdata md ON md.uid=t.authorid LEFT JOIN pw_polls p ON p.tid=t.tid";
	(!is_numeric($forumnum) || $forumnum<0) && $forumnum = 0;
	!$step && $step=1;
	!$percount && $percount=100;
	$start = ($step-1)*$percount;
	$next  = $start+$percount;
	$step++;
	$j_url = "$basename&action=$action&percount=$percount&creatfid=$fids&forumnum=$forumnum";
	$goon  = 0;

	$topicdb = $articledb = array();
	$query = $db->query("SELECT t.* $S_sql $fieldadd FROM pw_threads t $J_sql $tableadd $creatadd ORDER BY topped DESC,lastpost DESC".pwLimit($start,$percount));
	while ($topic = $db->fetch_array($query)) {
		if (!$topic['tid']) continue;
		$goon  = 1;
		$tids .= $topic['tid'].',';
		$topicdb[$topic['tid']] = $topic;
		$ttable_a[GetTtable($topic['tid'])][] = $topic['tid'];
		$ptable_a[$topic['ptable']][] = $topic['tid'];
	}
	if ($forumnum && $next >= $forumnum) {
		$goon = 0;
	}
	foreach ($ttable_a as $pw_tmsgs => $value) {
		$value = pwImplode($value);
		$query = $db->query("SELECT * FROM $pw_tmsgs WHERE tid IN($value)");
		while ($rt = $db->fetch_array($query)) {
			$topicdb[$rt['tid']] = array_merge($topicdb[$rt['tid']],$rt);
//			$topicdb[$rt['tid']] += $rt;//ifmark记录出不来
		}
	}
	$tids = substr($tids,0,-1);

	if ($tids) {
		$readnum = $db_readperpage - 1;
		foreach ($ptable_a as $key => $value) {
			$pw_posts = GetPtable($key);
			$value = pwImplode($value);
			$query = $db->query("SELECT t.*,m.uid,m.username,m.oicq,m.groupid,m.memberid,m.icon AS micon,m.hack,m.honor,m.signature,m.regdate,m.medals,m.userstatus,md.onlinetime,md.postnum,md.digests,md.rvrc,md.money,md.credit,md.currency,md.starttime,md.thisvisit $fieldadd FROM $pw_posts t LEFT JOIN pw_members m ON m.uid=t.authorid LEFT JOIN pw_memberdata md ON md.uid=t.authorid $tableadd WHERE t.tid IN($value) AND ifcheck=1 ORDER BY postdate");
			while ($article = $db->fetch_array($query)) {
				if (!is_array($articledb[$article['tid']])) settype($articledb[$article['tid']],'array');
				$articledb[$article['tid']][] = $article;
			}
		}
		unset($tids);
	}
	$db->free_result($query);
	//ob_end_clean();
	foreach ($topicdb as $key => $read) {
		$readdb = $votedb = $advertdb = array();
		$fid = $read['fid'];
		$tid = $read['tid'];
		$header_ad = $footer_ad = '';
		$advertdb  = AdvertInit('read',$fid);
		if (is_array($advertdb['header'])) {
			$header_ad = $advertdb['header'][array_rand($advertdb['header'])]['code'];
		}
		if (is_array($advertdb['footer'])) {
			$footer_ad = $advertdb['footer'][array_rand($advertdb['footer'])]['code'].'<br />';
		}
		$date = date('ym',$read['postdate']);
		$page = 1;
		$read['pid'] = 'tpc';
		$count = $read['replies']+1;
		if ($read['special'] == 1) {
			$voters			= $read['voters'];
			$modifiable		= $read['modifiable'];
			$previewable	= $read['previewable'];
			$multi			= $read['multiple'] ? $read['mostvotes'] : 0;
			$vote_close		= ($read['state'] || ($read['timelimit'] && $timestamp - $read['postdate'] > $read['timelimit'] * 86400)) ? 1 : 0;
			$tpc_date		= get_date($read['postdate']);
			$tpc_endtime	= $read['timelimit'] ? get_date($read['postdate']+$read['timelimit']*86400) : 0;
			htmvote($read['voteopts'], $read['multiple'], $previewable);
		}
		$readdb[]  = htmread($read,0);
		$authorids = array($read['authorid']);
		unset($topicdb[$key]);
		$subject	= $read['subject'];
		$tpctitle	= '- '.$subject;
		$favortitle	= str_replace("&#39","‘",$subject);
		$titletop1	= substrs('Re:'.str_replace('&nbsp;',' ',$subject),$GLOBALS['db_titlemax']-2);

		$j_p = "$R_url/$db_htmdir/$fid/$date/$tid.html";
		list($guidename,$forumtitle) = getforumtitle(forumindex($foruminfo['fup'],1),1);
		$guidename .= " <span class=\"crumbs-item current\"><i> </i><strong><a href=\"read.php?tid=$tid\">$subject</a></strong>";
		$forumtitle = "|$forumtitle";
		$db_metakeyword = "$subject".str_replace(array('|',' - '),',',$forumtitle).'phpwind';
		$read['content'] && $db_metadescrip = substrs(strip_tags(str_replace('"','&quot;',$read['content'])),50);
		$msg_guide = headguide($guidename);
		unset($fourm,$guidename);

		if ($read['replies'] > 0) {
			$floors = 1;
			if ($articledb[$tid]) {
				foreach ($articledb[$tid] as $key => $read) {
					$readdb[] = htmread($read,$floors);
					$authorids[] = $read['authorid'];
					unset($articledb[$tid][$key]);
					$floors++;
					if($floors>9)break;
				}
			}
			unset($sign);
		}
		$authorids = pwImplode($authorids);
		if ($db_showcolony) {
			$colonydb = array();
			$query = $db->query("SELECT c.uid,cy.id,cy.cname FROM pw_cmembers c LEFT JOIN pw_colonys cy ON cy.id=c.colonyid WHERE c.uid IN($authorids) AND c.ifadmin!='-1'");
			while ($rt = $db->fetch_array($query)) {
				if (!$colonydb[$rt['uid']]) {
					$colonydb[$rt['uid']] = $rt;
				}
			}
		}
		if ($db_showcustom) {
			$cids = $customdb = array();
			foreach ($_CREDITDB as $key => $value) {
				if (strpos($db_showcustom,",$key,") !== false) {
					$cids[] = $key;
				}
			}
			if ($cids) {
				$cids = pwImplode($cids);
				$query = $db->query("SELECT uid,cid,value FROM pw_membercredit WHERE uid IN($authorids) AND cid IN($cids)");
				while ($rt = $db->fetch_array($query)) {
					$customdb[$rt['uid']][$rt['cid']] = $rt['value'];
				}
			}
		}
		$name = $forum[$fid]['name'];
		if ($count%$db_readperpage == 0) { //$count $db_readperpage read.php?fid=$fid&tid=$tid&
			$numofpage = $count/$db_readperpage;
		} else {
			$numofpage = floor($count/$db_readperpage)+1;
		}
		$pages = numofpage($count,$page,$numofpage,"$url?fid=$fid&tid=$tid&");//文章数,页码,共几页,路径
		if (!is_dir(R_P.$db_htmdir.'/'.$fid)) {
			@mkdir(R_P.$db_htmdir.'/'.$fid);
			@chmod(R_P.$db_htmdir.'/'.$fid,0777);
			writeover(R_P."$db_htmdir/$fid/index.html",'');
			@chmod(R_P."$db_htmdir/$fid/index.html",0777);
		}
		if (!is_dir(R_P.$db_htmdir.'/'.$fid.'/'.$date)) {
			@mkdir(R_P.$db_htmdir.'/'.$fid.'/'.$date);
			@chmod(R_P.$db_htmdir.'/'.$fid.'/'.$date,0777);
			writeover(R_P."$db_htmdir/$fid/$date/index.html",'');
			@chmod(R_P."$db_htmdir/$fid/$date/index.html",0777);
		}
		ob_start();
		include Pcv(R_P."template/$tplpath/$output.htm");
		$content = str_replace(array('<!--<!---->','<!---->'),array('',''),ob_get_contents());
		$content.= "<script language=\"JavaScript\" src=\"http://init.phpwind.net/init.php?sitehash={$db_sitehash}&v=$wind_version&c=$ceversion\"></script>";
		ob_end_clean();
		writeover(R_P."$db_htmdir/$fid/$date/$tid.html",$content,"rb+",0);
		@chmod(R_P."$db_htmdir/$fid/$date/$tid.html",0777);
	}
	if ($goon) {
		$j_url .= "&step=$step&tfid=$tfid";
		adminmsg('updatecache_step',EncodeUrl($j_url));
	} else {
		$tfid++;
		if (isset($creatfid[$tfid])) {
			$j_url .= "&step=1&tfid=$tfid";
			adminmsg('updatecache_step1',EncodeUrl($j_url));
		}
		adminmsg('operate_success');
	}
} elseif ($_POST['action'] == 'delete') {

	@include_once(D_P.'data/bbscache/forum_cache.php');
	InitGP(array('creatfid'),'P');
	if (in_array('all',$creatfid)) {
		$handle = opendir(R_P.$db_htmdir.'/');
		while ($file = readdir($handle)) {
			if (($file != ".") && ($file != "..") && ($file != "")) {
				if (is_dir(R_P.$db_htmdir.'/'.$file)){
					//cms
					if (!$forum[$file]['cms']) {
						deldir(R_P.$db_htmdir.'/'.$file);
					}
					//cms
				}
			}
		}
	} elseif ($creatfid) {
		foreach ($creatfid as $key => $value) {
			if (is_numeric($value)) {
				deldir(R_P.$db_htmdir.'/'.$value);
			}
		}
	} else {
		adminmsg('forumid_error');
	}
	adminmsg('operate_success');
}
function AdvertInit($SCR,$fid) {
	global $timestamp,$db_advertdb;
	$newadvert = array();
	foreach ($db_advertdb as $key => $val) {
		foreach ($val as $k => $v) {
			if (!$v['endtime'] || $v['endtime'] < $timestamp) {
				continue;
			}
			if ($SCR == 'read' && strpos(",$v[fid],",",-3,") !== false) {
				$newadvert[$key][] = $v;
			} elseif (strpos(",$v[fid],",",-4,") !== false) {
				$newadvert[$key][] = $v;
			} elseif ($fid && strpos(",$v[fid],",",$fid,") !== false) {
				$newadvert[$key][] = $v;
			}
		}
	}
	return $newadvert;
}
function readad($ads,$lou,$p) {
	if(!$ads || !is_array($ads) || !$lou) return false;
	shuffle($ads);
	foreach ($ads as $k => $v) {
		if ($v['position']==$p && (strpos(",$v[lou],",',-1,')!==false || strpos(",$v[lou],",",$lou,")!==false)) {
			return $v['code'];
		}
	}
	return false;
}
?>